# -*- coding: utf-8 -*-

from legendaryPowerClientScript.ui.base.uiBase import UIBase
from legendaryPowerClientScript.util import apiUtil
from mod.client import extraClientApi
from templateScript import templateClientSystem


# UI类，一定要继承UIBase
class ShowItemsUI(UIBase):


    # 下面这两行别动
    def __init__(self, namespace, name, param):
        UIBase.__init__(self, namespace, name, param)
        from templateScript import templateClientSystem
        #监听服务端发来的事件
        templateClientSystem.mainSys.RegisterEventServerUI("ViewItemsEvent", self, self.HandleEventUI)
        print "Init ShowItemsUI"


    def Create(self):
        print "Create ShowItemsUI"
        # 在Create中才能正常获取到UI元素，构建界面
        #初始化滚动列表，字典中的元素类型为Item。详见 ListComponent 的文档
        self.itemsList = self.getList("/list_frame/items", {"typeHint": "Item"})
        self.itemsList.setAddElementCallback(self.onAddItemButton)
        self.closeButton = self.getButton("/list_frame/close")
        self.closeButton.SetTouchUp(self.onPressClose)

    def onPressClose(self, args):
        apiUtil.CloseGui(self)

    def onAddItemButton(self, button):
        #列表中增加元素时，会调用此函数。传入的button是列表中新增的元素
        button.getButton("image/claim").SetTouchUp(self.onPressClaim)

    def onPressClaim(self, args):
        #客户端告诉服务端自己点了哪个界面的哪个选项，具体发放什么，是否能发放一定要在处理时由服务端检查！
        index = int(args["ButtonPath"].split("_")[-1].split("/")[0])
        templateClientSystem.mainSys.NotifyToServer("ClientClaimViewItems", {
            "playerId": extraClientApi.GetLocalPlayerId(),
            "index": index
        })
        self.itemsList.GetElement(index).SetTouchEnable(False)

    def onRecievedEvent(self, data):
        #接收到事件，打开UI并完成界面的构建之后，此函数会被调用
        self.itemsList.SetElementSize(len(data))
        for i, itemData in enumerate(data):
            ele = self.itemsList.GetElement(i)
            ele.SetItem(itemData["item"])
            lores = apiUtil.formatVanillaDesc(itemData["item"])
            if lores:
                ele.getLabel("image/itemName").SetText(lores[0])
            ele.getButton("image/claim").SetTouchEnable(itemData["got"] == 0)